﻿using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Serialization;
using Microsoft.VisualBasic;

namespace Web_Oto.Common
{
    public partial class CommonHelper
    {
        public static string RemoveSpecialChars(string str)
        {
            string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "_", "(", ")", ":", "|", "[", "]" };

            for (int i = 0; i < chars.Length; i++)
            {
                if (str.Contains(chars[i]))
                {
                    str = str.Replace(chars[i], "");
                }
            }
            return str;
        }
        public static bool IsValidEmail(string email)
        {
            bool result = false;
            if (String.IsNullOrEmpty(email))
                return result;
            email = email.Trim();
            result = Regex.IsMatch(email,
                                   @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            return result;
        }

        public static string NiceUrl(string title)
        {
            const string textToFind = "áàảãạâấầẩẫậăắằẳẵặđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠÂẤẦẨẪẬĂẮẰẲẴẶĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ";
            const string textToReplace = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";

            int index = -1;
            while ((index = title.IndexOfAny(textToFind.ToCharArray())) != -1)
            {
                int index2 = textToFind.IndexOf(title[index]);
                title = title.Replace(title[index], textToReplace[index2]);
            }
            return title.Replace(" ", "-");
        }

        public static string FormatMultiline(string text)
        {
            if (text == null)
            {
                return "";
            }
            string result = text;
            if (result.Length > 0)
            {
                result = result.Replace(Constants.vbCr + Constants.vbLf, Constants.vbLf);
                result = result.Replace(Constants.vbCr, Constants.vbLf);
                result = result.Replace(Constants.vbLf, "<br />");
                return result;
            }
            else
            {
                return text;
            }
        }

        public static bool IsCurrentConnectionSecured(HttpContext context)
        {
            bool useSSL = false;
            if (context != null && context.Request != null)
            {
                useSSL = context.Request.IsSecureConnection;
            }

            return useSSL;
        }

        /// <summary>
        /// Sets cookie
        /// </summary>
        /// <param name="cookieName">Cookie name</param>
        /// <param name="cookieValue">Cookie value</param>
        /// <param name="ts">Timespan</param>
        public static void SetCookie(string cookieName, string cookieValue, TimeSpan ts)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Value = HttpContext.Current.Server.UrlEncode(cookieValue);
                DateTime dt = DateTime.Now;
                cookie.Expires = dt.Add(ts);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.Message);
            }
        }

        /// <summary>
        /// Gets cookie string
        /// </summary>
        /// <param name="cookieName">Cookie name</param>
        /// <param name="decode">Decode cookie</param>
        /// <returns>Cookie string</returns>
        public static string GetCookieString(string cookieName, bool decode)
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Request.Cookies[cookieName] == null)
                {
                    return string.Empty;
                }
                try
                {
                    string tmp = HttpContext.Current.Request.Cookies[cookieName].Value.ToString();
                    if (decode)
                        tmp = HttpContext.Current.Server.UrlDecode(tmp);
                    return tmp;
                }
                catch
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Gets boolean value from cookie
        /// </summary>
        /// <param name="cookieName">Cookie name</param>
        /// <returns>Result</returns>
        public static bool GetCookieBool(string cookieName)
        {
            string str1 = GetCookieString(cookieName, true).ToUpperInvariant();
            return (str1 == "TRUE" || str1 == "YES" || str1 == "1");
        }

        /// <summary>
        /// Generate random digit code
        /// </summary>
        /// <param name="length">Length</param>
        /// <returns>Result string</returns>
        public static string GenerateRandomDigitCode(int length)
        {
            var random = new Random();
            string str = string.Empty;
            for (int i = 0; i < length; i++)
                str = String.Concat(str, random.Next(10).ToString());
            return str;
        }

        public static void Log(string logMessage, TextWriter w)
        {
            w.Write("\r\nLog Entry : ");
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                        DateTime.Now.ToLongDateString());
            w.WriteLine("  :");
            w.WriteLine("  :{0}", logMessage);
            w.WriteLine("-------------------------------");
            // Update the underlying file.
            w.Flush();
        }

        public static void WriteLog(string logMessage)
        {
            try
            {
                using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath("~/log.txt")))
                {
                    Log(logMessage, w);
                    // Close the writer and underlying file.
                    w.Close();
                }
            }
            catch
            {
                ;
            }
        }

        /// <summary>
        /// Serializes a datetime
        /// </summary>
        /// <param name="dateTime">Datetime</param>
        /// <returns>Serialized datetime</returns>
        public static string SerializeDateTime(DateTime dateTime)
        {
            var xmlS = new XmlSerializer(typeof (DateTime));
            var sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                xmlS.Serialize(sw, dateTime);
                return sb.ToString();
            }
        }

        /// <summary>
        /// Deserializes a datetime
        /// </summary>
        /// <param name="dateTime">Datetime</param>
        /// <returns>Deserialized datetime</returns>
        public static DateTime DeserializeDateTime(string dateTime)
        {
            var xmlS = new XmlSerializer(typeof (DateTime));
            using (StringReader sr = new StringReader(dateTime))
            {
                object test = xmlS.Deserialize(sr);
                return (DateTime) test;
            }
        }

        public static string EncryptPwdSha512(string pwd)
        {
            SHA512 sha512 = new SHA512Managed();
            var sha512Bytes = Encoding.Default.GetBytes(pwd);
            var cryString = sha512.ComputeHash(sha512Bytes);
            var sha512Str = string.Empty;
            for (var i = 0; i < cryString.Length; i++)
            {
                sha512Str += cryString[i].ToString("X");
            }
            return sha512Str;
        }

        public static string GetMd5Hash(string input)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
                var sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                return sBuilder.ToString();
            }
        }

        public static bool VerifyMd5Hash(string input, string hash)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                string hashOfInput = GetMd5Hash(input);
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(hashOfInput, hash))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public static string ReadTemplate(string template)
        {
            var content = String.Empty;
            try
            {
                using (var dr = new StreamReader(template))
                {
                    content = dr.ReadToEnd();
                }
            }
            catch
            {
            }
            return content;
        }

        #region File
        public static string GetFilePath(string path, ref string fileName, string oldFilePath = "")
        {
            oldFilePath = path + @"/" + oldFilePath;
            oldFilePath = HttpContext.Current.Server.MapPath(oldFilePath);            

            if (!string.IsNullOrEmpty(oldFilePath))
                if (File.Exists(oldFilePath))
                    File.Delete(oldFilePath);

            fileName = NiceUrl(fileName);
            var filePath = path + @"/" + fileName;
            filePath = HttpContext.Current.Server.MapPath(filePath);
            var extension = Path.GetExtension(fileName);
            if (extension != null) fileName = fileName.Replace(extension, "");

            if (File.Exists(filePath))
            {
                var timeString = DateTime.Now.ToString("yyyy-MM-dd-mm-hh-ss");
                fileName = fileName + "-" + timeString;
            }
            fileName = fileName + extension;

            var newfilePath = path + @"/" + fileName;

            return newfilePath;
        }

        public static bool DeleteFile(string path, string fileName)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                var filePath = path + @"/" + fileName;
                filePath = HttpContext.Current.Server.MapPath(filePath);
                if (File.Exists(filePath))
                    File.Delete(filePath);
            }
            
            return true;
        }

        #endregion File
    }
}
